/*
*  Description: java pipeline as code
*  Date: 2021-10-01 08:54
*  Author: gaowei
*/
def call(Map map) {
    pipeline {

        agent {
            kubernetes {
                defaultContainer 'kaniko'
                yaml libraryResource("KubernetesPod.yaml")
            }

        }

        options {
            buildDiscarder(logRotator(numToKeepStr: '50'))
            disableConcurrentBuilds()
            timeout(time: 30, unit: 'MINUTES')
        }

        environment {
            APP = "${map.app}"
            LANG = "${map.lang}"
            ARTIFACT = "${map.artifact}"
            NS = "${map.namespace}"
            IMAGE_NAME = "swr.cn-north-4.myhuaweicloud.com/g84245587/${JOB_NAME}:${BUILD_ID}"
        }

        parameters {
            choice(name: 'BUILD_ENV', choices: 'dev\ntest\nuat', description: '请选择部署环境:')
            gitParameter(branchFilter: 'origin/(.*)', defaultValue: 'dev', name: 'BUILD_BRANCH', type: 'PT_BRANCH', description: '请选择分支:', useRepository: "${map.git}")
        }

        stages {

            stage('认证') {
                when {
                    expression {
                        return !isDev()
                    }
                }
                steps {
                    script {
                        auth()
                    }
                }
            }

            stage('拉取代码') {
                steps {
                    script {
                        git branch: "${params.BUILD_BRANCH}", url: map.git
                    }
                }
            }

            stage('编译') {
                when {
                    expression {
                        return isIgnore(map)
                    }
                }
                steps {
                    container('nodejs') {
                        sh "npm install --registry=https://registry.npm.taobao.org"
                        sh "npm run build"
                    }
                }
            }

            stage('构建镜像') {
                steps {
                    configFileProvider([configFile(fileId: "Dockerfile_npm", variable: 'DOCKER_FILE')]) {
                        sh "/kaniko/executor --context=${WORKSPACE} -f `pwd`/Dockerfile -c `pwd` --build-arg JAR_PATH=${ARTIFACT} --insecure --skip-tls-verify --cache=true --destination=${IMAGE_NAME}"
                    }
                }
            }

            stage('部署') {
                environment {
                    AN_KUBE_CONFIG = credentials("${params.BUILD_ENV}-kubeconfig")
                }
                steps {
                    container('kubectl') {
                        script {
                            sh "kubectl --kubeconfig ${AN_KUBE_CONFIG} -n ${env.NS} set image deployment ${env.APP} ${env.APP}=${IMAGE_NAME}"
                        }
                    }
                }
            }

        }


    }
}